/* @flow */

import React, {Component} from 'react';
import {
  View,
  Text,
  StyleSheet,
  Image,
  Button,
  ScrollView,
  TouchableOpacity
} from 'react-native';
import PropTypes from 'prop-types'

import {connect} from 'react-redux';
import {testAction, showTabBar} from '../../Redux/actions/AppActions.js'
// var githubicon = 'https://ws3.sinaimg.cn/large/006tNc79ly1fift1efkwyj30dw0dwglv.jpg';
// var searchicon = 'https://ws4.sinaimg.cn/large/006tNc79ly1fifwklyrpjj301o01ogld.jpg'
// var paopao = 'https://ws1.sinaimg.cn/large/006tNc79ly1ficcfl33d7j300u00o0sh.jpg';
// var reacticon = 'https://ws1.sinaimg.cn/large/006tNc79ly1fhp9dw6vxpj307406ewek.jpg';
var Dimensions = require('Dimensions');
var {width} = Dimensions.get('window');
// 引入计时器类库
var TimerMixin = require('react-timer-mixin');
var cols = 3;
var vmargin = 1;
var boxW = (width - ((cols + 1) * vmargin)) / cols;
var boxH = 80;
var hMargin = 1;
var acols = 2;
var avmargin = 20;
var aboxW = (width - ((acols + 1) * avmargin)) / acols;
var aboxH = 40;
var ahMargin = 0;
var moodData = require('./FMFind/moodData.json');
var sceneData = require('./FMFind/sceneData.json');
class AppFind extends Component {

  static navigationOptions = ({navigation, screenProps}) => {
    const {navigate, state} = navigation;
    var title = state.params && state.params.title;

    return {
      headerTitle: '发现', header: <View></View>,

      //tabbar
      tabBarIcon: ({focused, tintColor}) => {

        return (<Image source={focused
          ? require('../img/tabicon/faxianSelectedXiong1.png')
          : require('../img/tabicon/faxianXiong1.png')} style={[styles.icon]}/>)
      },
      // tabBarLabel: 'First',

    }
  }

  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      anchorData: [],
      imageAA: '',
      // 当前的页码
      currentPage: 0,
      // 注册计时器
    }
  }

  _scrollView : ScrollView;
  renderPosterItem = () => {
    let itemArray = [];
    for (let i = 0; i < this.state.dataSource.length; i++) {
      var itemDic = this.state.dataSource[i];
      console.log('========' + itemDic.cover);
      itemArray.push(
        <View key={i} style={styles.itemStyle}>
          <Image source={{
            uri: itemDic.cover
          }} style={{
            width: width,
            height: 250
          }}/>
          <View style ={{
            position: 'absolute',
            bottom: 15,
            backgroundColor: 'transparent'
          }}>
            <Text style={{
              color: 'white',
              fontSize: 15
            }}>{itemDic.title}</Text>
          </View>
        </View>
      );
    }
    return itemArray;
  }

  moodContentTtem = () => {
    var allImages = [];

    var allContentImages = moodData.data;
    console.log('dddddllll' + allContentImages);

    for (let i = 0; i < allContentImages.length; i++) {
      let imageContent = allContentImages[i];
      allImages.push(
        <View key ={i} style ={styles.innerImagesStyle}>
          <TouchableOpacity onPress ={() => this.props.navigation.navigate('BroadCastList', {broadCastList: imageContent})}>
            <Image source ={{
              uri: imageContent.img
            }} style ={styles.imageContentStyle}/>
            <Text>{imageContent.title}</Text>
          </TouchableOpacity>

        </View>

      );

    }

    return allImages;

  }

  moodTtem = () => {
    return (
      <View>
        <Text style={{
          marginTop: 15,
          marginLeft: 10,
          fontSize: 20
        }}>心情</Text>
        <View style={styles.moodContrentViewStyle}>
          {this.moodContentTtem()}
        </View>

      </View>
    );
  }

  sceneContentTtem = () => {
    var allImages = [];

    var allContentImages = sceneData.data;
    console.log('dddddllll' + allContentImages);

    for (let i = 0; i < allContentImages.length; i++) {
      let imageContent = allContentImages[i];
      console.log(imageContent.img);
      allImages.push(
        <View key ={i} style ={styles.innerImagesStyle}>
          <TouchableOpacity onPress ={() => this.props.navigation.navigate('BroadCastList', {broadCastList: imageContent})}>
            <Image source ={{
              uri: imageContent.img
            }} style ={styles.imageContentStyle}/>
            <Text>{imageContent.title}</Text>
          </TouchableOpacity>

        </View>

      );

    }

    return allImages;

  }

  sceneItem = () => {
    return (
      <View>
        <Text style={{
          marginTop: 15,
          marginLeft: 10,
          fontSize: 20
        }}>场景</Text>
        <View style={styles.moodContrentViewStyle}>
          {this.sceneContentTtem()}
        </View>

      </View>
    );
  }

  anchorContentItem = () => {

    var allImages = [];

    var allContentImages = this.state.anchorData;
    console.log('dddddllll' + allContentImages);

    for (let i = 0; i < allContentImages.length; i++) {
      let imageContent = allContentImages[i];
      console.log(imageContent);
      allImages.push(
        <View key ={i} style ={styles.innerAnchorImagesStyle}>
          <TouchableOpacity onPress= {()=>this.props.navigation.navigate('Anchor',{anchor:imageContent})}>
            <View style={styles.anchorContentInnerStyle}>
              <Image source ={{
                uri: imageContent.cover
              }} style ={styles.imageAnchorContentStyle}/>
              <View style={styles.rightAnchorStyle}>
                <Text style={{
                  fontSize: 15
                }}>{imageContent.title}</Text>
                <Text style={{
                  fontSize: 13,
                  color: '#333333'
                }}>{'节目' + imageContent.fmnum}</Text>
              </View>
            </View>
          </TouchableOpacity>

          {/* </TouchableOpacity> */}

        </View>

      );

    }

    return allImages;
  }

  anchorItem = () => {
    return (
      <View >
        <TouchableOpacity onPress= {()=>this.props.navigation.navigate('AllAnchor',{anchorList:'主播列表'})}>
          <View style={styles.anchorfrontStyle}>
            <Text style={{
              marginTop: 15,
              marginLeft: 10,
              fontSize: 20
            }}>主播</Text>
            <Image source={require('../img/findicon/detail.png')}
             style={{
              width: 9,
              height: 17,
              marginTop: 30,
              marginRight: 30
            }}/>

          </View>
        </TouchableOpacity>

        <View style={styles.anchorContentViewStyle}>
          {this.anchorContentItem()}
        </View>
      </View>
    );
  }

  componentWillMount() {
    this.fetchData('http://bapi.xinli001.com/fm2/hot_tag_list.json/?flag=4&key=c0d28ec0954084b4426223366293d190&rows=3&offset=0');
    this.fetchAnchorData('http://yiapi.xinli001.com/fm/diantai-find-list.json?key=c0d28ec0954084b4426223366293d190&rows=6&offset=0');

  }
  fetchAnchorData = (url) => {
    fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
      // body:JSON.stringify({
      //   // "page":index,
      // })
    }).then((response) => response.json()).then((responseData) => {

      // let rowData = Array.from(responseData.data.articles);
      console.log(responseData.data);
      this.setState({
        anchorData: this.state.anchorData.concat(responseData.data),
        // dataSource:(responseData.data),
        //  dataSource:this.state.dataSource.concat(responseData.data.articles),
        refreshing: false
      });
      // dataSource:this.state.dataSource.concat(this.state.dataSource)

    });

  }
  fetchData = (url) => {
    fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
      // body:JSON.stringify({
      //   // "page":index,
      // })
    }).then((response) => response.json()).then((responseData) => {

      // let rowData = Array.from(responseData.data.articles);
      console.log(responseData.data);
      this.setState({
        dataSource: this.state.dataSource.concat(responseData.data),
        // dataSource:(responseData.data),
        //  dataSource:this.state.dataSource.concat(responseData.data.articles),
        refreshing: false
      });
      // dataSource:this.state.dataSource.concat(this.state.dataSource)

    });

  }

  // 实现一些复杂的操作
  componentDidMount() {
    // 开启定时器
    this.startTimer();
  }
  _findOnMomentumScrollEnd = (e) => {
    var offsetX = e.nativeEvent.contentOffset.x;

    var currentPage = Math.floor(offsetX / width);

    this.setState({currentPage: currentPage});

  }

  _findOnScrollBeginDrag = () => {

    clearInterval(this.timer);

  }
  _findOnScrollEndDrag = () => {
    this.startTimer();
  }
  startTimer = () => {
    var imageCount = this.state.dataSource.length;

    this.timer = setTimeout(() => {
      var activePage = 0;
      if ((this.state.currentPage + 1) >= imageCount) {
        activePage = 0;
      } else {
        activePage = this.state.currentPage + 1;
      }
      this.setState({currentPage: activePage});

      var offSetX = activePage * width;
      _scrollView.scrollTo({x: offSetX, y: 0, animated: true})

    }, 1000);

  }

  renderPosterPoint=() => {
    var postPointData = [];
    var imageCount = this.state.dataSource.length;
    for (var i = 0; i < imageCount.length; i++) {

      postPointData.push(
        <Text
          key = {i}
          style = {{fontSize:25,color:this.state.currentPage == i?'white':'red',backgroundColor:'transparent'}}
          >
            dddddd
          </Text>
      )
    }
    return postPointData;
  }

  render() {
    return (
      <View style={styles.container}>
      <ScrollView>


        <ScrollView style={styles.innerScrollViewStyle}
        ref={(scrollView) => {
        _scrollView = scrollView
        }}
        horizontal={true}
        showsHorizontalScrollIndicator={false}
        pagingEnabled={true}
        onMomentumScrollEnd={this._findOnMomentumScrollEnd}
        onScrollBeginDrag ={this._findOnScrollBeginDrag}
        onScrollEndDrag ={this._findOnScrollEndDrag}
        >
        {this.renderPosterItem()}
          </ScrollView>
          {/* <View style={styles.circleViewStyle}>
            {this.renderPosterPoint()}
          </View> */}



          <View style={styles.moodStyle}>
            {this.moodTtem()}
          </View>
          <View style={styles.sceneStyle}>
            {this.sceneItem()}
          </View>
          <View style={styles.anchorStyle}>
            {this.anchorItem()}
          </View>

        </ScrollView>
      </View>

    );
  }

  _pushAction = () => {

    this.props.changeTabBar(!this.props.testShow);

    // this.props.navigation.navigate('search',{name:'search params',showTab:false})
  }
}

const styles = StyleSheet.create({
  container: {
    marginTop: 0,
    flex: 1
  },
  innerScrollViewStyle: {
    // 背景色
    // backgroundColor:'red',
    flexDirection: 'row'
  },
  circleViewStyle: {
    width:width,
    height:85,
    position:'absolute',
    bottom:0,
    backgroundColor:'blue',
    flexDirection:'row',
    justifyContent:'center',
    alignItems:'flex-end',
  },

  itemStyle: {
    // 尺寸
    width: width,
    height: 250,
    // backgroundColor:'blue',
    flexDirection: 'column',
    alignItems: 'center'
  },
  moodStyle: {
    flexDirection: 'column'
  },
  sceneStyle: {
    flexDirection: 'column'
  },
  moodContrentViewStyle: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginTop: 10
  },
  innerImagesStyle: {
    width: boxW,
    height: boxW,
    marginLeft: vmargin,
    marginTop: hMargin,
    marginBottom: hMargin,
    backgroundColor: 'white',
    alignItems: 'center',
    justifyContent: 'center'
  },
  imageContentStyle: {
    width: 30,
    height: 30
  },
  anchorfrontStyle: {
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  anchorContentViewStyle: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginTop: 10
  },

  innerAnchorImagesStyle: {
    width: aboxW,
    height: 100,
    marginLeft: avmargin,
    marginTop: ahMargin,
    marginBottom: ahMargin,
    // backgroundColor:'white',
    // alignItems:'center',
    // justifyContent:'center',
  },
  anchorContentInnerStyle: {
    flexDirection: 'row',
    width: 150,
    height: 60
  },
  imageAnchorContentStyle: {
    width: 60,
    height: 60,
    borderRadius: 30
  },
  rightAnchorStyle: {
    flexDirection: 'column',
    alignItems: 'flex-start',
    justifyContent: 'center',
    marginLeft: 10
  }
});

//用来获取更新后的数据   监听数据更新
const mapStateToProps = (state, ownProps) => {
  console.log(state);
  return {testShow: state.find.testShow}
}

//用来派发消息
const mapDispatchToProps = (dispatch, ownProps) => ({
  changeTabBar: (...args) => dispatch(showTabBar(...args))
});

//用来进行数据流  和  控件的绑定关系
export default connect(mapStateToProps, mapDispatchToProps)(AppFind)
